#include "spi.h"


/* SPI_SCK Port/Pin definition */
#define SPI_SCK_PORT                    (PortB)
#define SPI_SCK_PIN                     (Pin13)
#define SPI_SCK_FUNC                    (Func_Spi3_Sck)

/* SPI_MOSI Port/Pin definition */
#define SPI_MOSI_PORT                   (PortB)	
#define SPI_MOSI_PIN                    (Pin12)	
#define SPI_MOSI_FUNC                   (Func_Spi3_Mosi)	

/* SPI_MISO Port/Pin definition */
#define SPI_MISO_PORT                   (PortB)			
#define SPI_MISO_PIN                    (Pin14)			
#define SPI_MISO_FUNC                   (Func_Spi3_Miso)		

/* SPI unit and clock definition */
#define SPI_UNIT                        (M4_SPI3)			
#define SPI_UNIT_CLOCK                  (PWC_FCG1_PERIPH_SPI3)		
#define SPI_MASTER_MODE



void spiInit(void)			
{
    stc_spi_init_t stcSpiInit;
		
    /* configuration structure initialization */
    MEM_ZERO_STRUCT(stcSpiInit);
		
    /* Configuration peripheral clock */
    PWC_Fcg1PeriphClockCmd(SPI_UNIT_CLOCK, Enable);
		
    /* Configuration SPI pin */
    PORT_SetFunc(SPI_SCK_PORT, SPI_SCK_PIN, SPI_SCK_FUNC, Disable);
    //PORT_SetFunc(SPI_NSS_PORT, SPI_NSS_PIN, SPI_NSS_FUNC, Disable);
    PORT_SetFunc(SPI_MOSI_PORT, SPI_MOSI_PIN, SPI_MOSI_FUNC, Disable);
    PORT_SetFunc(SPI_MISO_PORT, SPI_MISO_PIN, SPI_MISO_FUNC, Disable);
		
    /* Configuration SPI structure */
    stcSpiInit.enClkDiv = SpiClkDiv64;
    stcSpiInit.enFrameNumber = SpiFrameNumber1;
    stcSpiInit.enDataLength = SpiDataLengthBit8;
    stcSpiInit.enFirstBitPosition = SpiFirstBitPositionMSB;
#if 1
    stcSpiInit.enSckPolarity = SpiSckIdleLevelLow;//SpiSckIdleLevelHigh;
    stcSpiInit.enSckPhase = SpiSckOddSampleEvenChange;//SpiSckOddSampleEvenChange
#else
    stcSpiInit.enSckPolarity = SpiSckIdleLevelHigh;//SpiSckIdleLevelHigh;
    stcSpiInit.enSckPhase = SpiSckOddChangeEvenSample;//SpiSckOddChangeEvenSample
#endif
    stcSpiInit.enReadBufferObject = SpiReadReceiverBuffer;
    stcSpiInit.enWorkMode = SpiWorkMode3Line;
    stcSpiInit.enTransMode = SpiTransFullDuplex;
    stcSpiInit.enCommAutoSuspendEn = Disable;
    stcSpiInit.enModeFaultErrorDetectEn = Disable;
    stcSpiInit.enParitySelfDetectEn = Disable;
    stcSpiInit.enParityEn = Disable;
    stcSpiInit.enParity = SpiParityEven;

    stcSpiInit.enMasterSlaveMode = SpiModeMaster;

    SPI_Init(SPI_UNIT, &stcSpiInit);
    SPI_Cmd(SPI_UNIT, Enable);
}


uint8_t spiRW(uint8_t data)
{
	while (Reset == SPI_GetFlag(SPI_UNIT, SpiFlagSendBufferEmpty))
	{;}	
	SPI_SendData8(SPI_UNIT, data);
	while (Reset == SPI_GetFlag(SPI_UNIT, SpiFlagReceiveBufferFull))
	{;}	
	data = SPI_ReceiveData8(SPI_UNIT);
	return data;
}

